package cn.tedu.context;

import cn.tedu.demo.Dept;
import cn.tedu.demo.Employee;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;
import java.util.Date;

@Configuration
@ComponentScan("cn.tedu.demo")
@PropertySource("classpath:jdbc.properties")
public class Config {
    @Autowired
    Environment env;

    @Bean
    public Date currentDate() {
        return new Date();
    }

    @Bean
    public Dept dept(Employee employee) {
        Dept dept = new Dept();
        dept.setManager(employee);
        return dept;
    }

    @Bean
    public DataSource dataSource3(
            @Value("${db.driver}") String driver,
            @Value("${db.url}") String url,
            @Value("${db.username}") String username,
            @Value("${db.password}") String password,
            @Value("${db.maxActive}") int maxActive,
            @Value("${db.initialSize}") int initialSize) {
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setMaxActive(maxActive);
        ds.setInitialSize(initialSize);
        return ds;
    }

    @Bean
    public DataSource dataSource2() {
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(env.getProperty("db.driver"));
        ds.setUrl(env.getProperty("db.url"));
        ds.setUsername(env.getProperty("db.username"));
        ds.setPassword(env.getProperty("db.password"));
        ds.setMaxActive(env.getProperty("db.maxActive", Integer.class));
        ds.setInitialSize(env.getProperty("db.initialSize", Integer.class));
        return ds;
    }

    @Bean
    public DataSource dataSource() {
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai");
        ds.setUsername("root");
        ds.setPassword("000000");
        ds.setMaxActive(10);
        ds.setInitialSize(2);
        return ds;
    }
}
